"use strict";

var commFun = {};
module.exports = commFun;

/**
 * 格式输出
 * @param errCode 0 ok, other:sth wrong
 * @param errMsg error message
 * @param data if errCode=0,the result
 * @returns {errCode: *, errMsg: *, result: *}
 */
commFun.formatOutput = function (errCode, errMsg, data) {
    let ret = {
        errCode: errCode,
        errMsg: errMsg
    };

    if (errCode === 0 && !data) {
        throw new Error('errCode=0 must have result object')
    }

    if (data) {
        if (typeof data === 'string') {
            ret.result = {
                msg: data
            }
        } else {
            ret.result = data;
        }
    }
    return ret;
};

commFun.formatOutput2 = function (errCode, errMsg, data) {
    let ret = {
        errCode: errCode,
        errMsg: errMsg
    };

    if (errCode === 0 && !data) {
        throw new Error('errCode=0 must have result object')
    }

    if (data) {
        if (Array.isArray(data)) {
            ret.result = data;
        } else {
            let obj = data;
            if (typeof data === 'string') {
                obj = {msg: data}
            }
            ret.result = [];
            ret.result.push(obj);
        }
    }
    return ret;
};


/**
 * md5摘要
 * @param str
 */
var crypto = require('crypto');
commFun.md5 = function (str) {
    var hash = crypto.createHash('md5').update(str).digest('hex');
    return hash;
};